/*
 * Copyright (C) 2011 Consulanza Informatica.
 * info@consulanza.it
 * 
 * This file is part of Customer Calls Tracker.
 *
 *    Customer Calls Tracker is free software: you can redistribute it and/or
 *    modify it under the terms of the GNU General Public License as published
 *    by the Free Software Foundation, either version 3 of the License, or (at 
 *    your option) any later version.
 *
 *    Customer Calls Tracker is distributed in the hope that it will be useful,
 *    but WITHOUT ANY WARRANTY; without even the implied warranty of
 *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General 
 *    Public License for more details.
 *
 *    You should have received a copy of the GNU General Public License
 *    along with Customer Calls Tracker. If not, see http://www.gnu.org/licenses/.
 *
 * Portions of this software is a derivate work from:
 *
 * Copyright (C) 2008 Google Inc.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package consulanza.amlsoft.customercalls;

import consulanza.amlsoft.customercalls.CustomerCallsDbAdapter.CustomerCall;
import android.app.Activity;
import android.app.Dialog;
import android.app.ListActivity;
import android.content.Intent;
import android.database.Cursor;
import android.os.Bundle;
import android.util.Log;
import android.view.ContextMenu;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ContextMenu.ContextMenuInfo;
import android.widget.ListView;
import android.widget.AdapterView.AdapterContextMenuInfo;

public class CallList extends ListActivity {
	private static final String TAG = "CustomerCalls CallList";
	private CustomerCallsDbAdapter mDbHelper;

    /**
     * Called when the activity is first created.
     */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.calls_list);
        mDbHelper = new CustomerCallsDbAdapter(this);
        mDbHelper.open();
        fillData();
        registerForContextMenu(getListView());
    }
    /**
     * 
     */
    private void fillData() {
        Cursor callsCursor = mDbHelper.fetchAllCalls();
        startManagingCursor(callsCursor);
        /*
         * imposta il CursorAdapter personalizzato per la visualizzazione delle righe
         * di elenco
         */
        String[] from = new String[]{};
        int[] to = new int[]{};
        CustomerCallsCursorAdapter calls = 
            new CustomerCallsCursorAdapter(this, R.layout.calls_row, callsCursor, from, to);
        setListAdapter(calls);
    }
    /**
     * setup menu
     */
    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        super.onCreateOptionsMenu(menu);
        menu.add(0, InterfaceIds.MENU_ID_INSERT, 		1, R.string.menu_insert_call);
        menu.add(0, InterfaceIds.MENU_ID_EXPORT_XML, 	2, R.string.menu_export_xml);
        menu.add(0, InterfaceIds.MENU_ID_IMPORT_XML, 	3, R.string.menu_import_xml);
        menu.add(0, InterfaceIds.MENU_ID_DELETE_BILLED,	4, R.string.menu_delete_billed);
        return true;
    }
    /**
     * process menu click
     */
    @Override
    public boolean onMenuItemSelected(int featureId, MenuItem item) {
        switch(item.getItemId()) {
        case InterfaceIds.MENU_ID_INSERT:
            createCall();
            return true;
        case InterfaceIds.MENU_ID_EXPORT_XML:
            exportXml();
            return true;
        case InterfaceIds.MENU_ID_IMPORT_XML:
            importXml();
            return true;
        case InterfaceIds.MENU_ID_DELETE_BILLED:
            deleteBilled();
            return true;
        }

        return super.onMenuItemSelected(featureId, item);
    }
    /**
     * Setup context menu
     */
    @Override
    public void onCreateContextMenu(ContextMenu menu, View v,
            ContextMenuInfo menuInfo) {
        super.onCreateContextMenu(menu, v, menuInfo);
        menu.add(0, InterfaceIds.MENU_ID_INSERT, 	0, R.string.menu_insert_call);
        menu.add(0, InterfaceIds.MENU_ID_EDIT, 		1, R.string.menu_edit_call);
        menu.add(0, InterfaceIds.MENU_ID_DELETE, 	2, R.string.menu_delete_call);
        menu.add(0, InterfaceIds.MENU_ID_SET_CALL_BILLED, 	3, R.string.menu_set_call_billed);
    }
    /**
     * process context menu click
     */
    @Override
    public boolean onContextItemSelected(MenuItem item) {
    	final AdapterContextMenuInfo info_row;
        switch(item.getItemId()) {
        	case InterfaceIds.MENU_ID_INSERT:
        		createCall();
        		return true;
        	case InterfaceIds.MENU_ID_EDIT:
                info_row = (AdapterContextMenuInfo) item.getMenuInfo();
	            Intent i = new Intent(this, CallEdit.class);
	            i.putExtra(CustomerCall.KEY_ROWID, info_row.id);
	            startActivityForResult(i, InterfaceIds.ACTIVITY_EDIT);
	            fillData();
	            return true;
	        case InterfaceIds.MENU_ID_DELETE:
                info_row = (AdapterContextMenuInfo) item.getMenuInfo();
                mDbHelper.deleteCall(info_row.id);
                fillData();
                return true;
	        case InterfaceIds.MENU_ID_SET_CALL_BILLED:
                info_row = (AdapterContextMenuInfo) item.getMenuInfo();
                mDbHelper.setBilled(info_row.id,true);
                fillData();
                return true;
        }
        return super.onContextItemSelected(item);
    }
    /**
     * start call creation activity
     */
    private void createCall() {
        Intent i = new Intent(this, CallEdit.class);
        startActivityForResult(i, InterfaceIds.ACTIVITY_CREATE);
    }
    /**
     * export database to XML
     */
    private void exportXml() {
    	mDbHelper.exportXml();
    	showDialog(InterfaceIds.DIALOG_ID_EXPORT_XML_DONE);
    }
    /**
     * delete already billed calls (calls with flag_billed = true)
     */
    private void deleteBilled() {
    	mDbHelper.deleteBilled(true);
    }
    /**
     * import XML to database
     */
    private void importXml() {
    	Intent i = new Intent(this, FileDialog.class);
    	i.putExtra(FileDialog.START_PATH, Common.PATH_SDCARD);
    	startActivityForResult(i, InterfaceIds.ACTIVITY_FILEDLG);
    }
    /**
     * import database from XML file
     */
    private void doImportXml(String filePath) {
    	mDbHelper.importXml(filePath);
    }
    /**
     * response to item click: edit item
     */
    @Override
    protected void onListItemClick(ListView l, View v, int position, long id) {
        Intent i = new Intent(this, CallEdit.class);
        i.putExtra(CustomerCall.KEY_ROWID, id);
        startActivityForResult(i, InterfaceIds.ACTIVITY_EDIT);   	
    }
    /**
     * fill data buffer upon return from item edit
     */
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent intent) {
        super.onActivityResult(requestCode, resultCode, intent);
        switch (requestCode) {
	        case InterfaceIds.ACTIVITY_EDIT:
	            fillData();
	            break;
	        case InterfaceIds.ACTIVITY_FILEDLG:
	        	onFiledialogResult(resultCode, intent);
	            break;
        }
    }
    /**
     * Callback for FileDialog activity (import). If a file was selected then
     * starts importing it into DB
     * 
     * @param resultCode
     * @param data
     */
    private void onFiledialogResult(int resultCode, Intent data) {
    	switch (resultCode) {
	    	case Activity.RESULT_OK:
	            String filePath = data.getStringExtra(FileDialog.RESULT_PATH);
	            doImportXml(filePath);
	            fillData();
	        	showDialog(InterfaceIds.DIALOG_ID_IMPORT_XML_DONE);
	            break;
	    	case Activity.RESULT_CANCELED:
	    	    Log.w(TAG,this.getString(R.string.warn_no_file_selected));
	    		break;
        }
    }    
    /**
     * handle dialogs creation
     */
    @Override
    protected Dialog onCreateDialog(int id) {
        switch(id) {
	        case InterfaceIds.DIALOG_ID_EXPORT_XML_DONE:
	        	return CommonDialogs.NotificationDialog(this,R.string.title_info, R.string.inf_export_xml_done);
	        //
	        case InterfaceIds.DIALOG_ID_IMPORT_XML_DONE:
	        	return CommonDialogs.NotificationDialog(this,R.string.title_info, R.string.inf_import_xml_done);
	        default:
	        	return null;
        }
    }
}